﻿#ifndef __SS_WRITE_BYTE_H__
#define __SS_WRITE_BYTE_H__
#include "../container/ssBuffer.h"
#include <string>

namespace StarSeeker
{

class ssWriteBytes
{
public:
	ssWriteBytes();
	ssWriteBytes(const ssWriteBytes& wb);
	ssWriteBytes(u32 size, MEM_MGR_TYPE type=MEM_MGR_FIXED_NEW);
	ssWriteBytes(char* buffer, u32 size);
	~ssWriteBytes();
	void operator = (const ssWriteBytes& wb);
	//动态创建一个缓存
	bool Set(u32 size, MEM_MGR_TYPE type=MEM_MGR_FIXED_NEW);
	//从外部传入一个缓存
	bool Set(char* buffer, u32 size);

	inline bool WriteChar(i8 data)
	{
		return WriteBuffer(&data, cg_i8_size);
	}
	inline bool WriteUChar(u8 data)
	{
		return WriteBuffer(&data, cg_u8_size);
	}
	inline bool WriteFloat(float data)
	{
		return WriteBuffer(&data, sizeof(float));
	}
	inline bool WriteDouble(double& data)
	{
		return WriteBuffer(&data, sizeof(double));
	}
	inline bool WriteI64(i64 data)
	{
		return WriteBuffer(&data, cg_i64_size);
	}
	inline bool WriteU64(u64 data)
	{
		return WriteBuffer(&data, cg_u64_size);
	}
	inline bool WriteI32(i32 data)
	{
		return WriteBuffer(&data, cg_i32_size);
	}
	inline bool WriteU32(u32 data)
	{
		return WriteBuffer(&data, cg_u32_size);
	}
	inline bool WriteI16(i16 data)
	{
		return WriteBuffer(&data, cg_i16_size);
	}
	inline bool WriteU16(u16 data)
	{
		return WriteBuffer(&data, cg_u16_size);
	}
	//仅写入一段数据,不带长度
	inline bool WriteData(const void* p, ulint size)
	{
		return WriteBuffer(p, size);
	}
	//写入一段数据,带4字节长度
	bool WriteString(const char* psz, ulint len);
	bool WriteString(std::string& str);
	bool WriteStruct(const void* pbuf, ulint len);
	//重置写入
	inline void Empty()
	{
		m_buffer.Empty();
	}
	//跳过一定长度
	inline bool Skip(u32 size)
	{
		return m_buffer.AddSize(size);
	}
	//返回缓存地址
	inline char* Buf()
	{
		return m_buffer.Buf();
	}
	//已写大小
	inline ulint Size()
	{
		return m_buffer.Size();
	}
	//剩余大小
	inline ulint RemainSize()
	{
		return m_buffer.ResidueSize();
	}
	//最大缓存大小
	inline ulint MaxSize()
	{
		return m_buffer.MaxSize();
	}
	//返回当前位置的缓存
	inline char* CurrentBuf()
	{
		return m_buffer.CurrentBuf();
	}
	//从新分配大小
	bool Resize(ulint size);
	//清理缓存
	void Clear();
private:
	//写数据
	bool WriteBuffer(const void* p, ulint size);
	//拷贝构造
	void CopyFrom(const ssWriteBytes& wb);

	ssBuffer	m_buffer;	// 缓存
};

}
#define SS_STACK_WRITER(name,len) char _ssWriteBytesArr_[len];StarSeeker::ssWriteBytes name;name.Set(_ssWriteBytesArr_,len)

#endif
